package com.wind.base;

import android.content.Context;
import android.content.Intent;
import android.graphics.Matrix;
import android.graphics.SurfaceTexture;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.transition.TransitionManager;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;


import com.wind.toastlib.ToastUtil;

import java.io.IOException;
import java.util.HashMap;

import butterknife.ButterKnife;


/**
 * Created by wind on 2017/2/9.
 */

public class VideoPlayerActivity extends BaseActivity implements TextureView.SurfaceTextureListener {

    public static void start(Context context, String videoUrl) {
        start(context,videoUrl,"视频");

    }
    public static void start(Context context, String videoUrl, String title) {
        Intent intent = new Intent(context, VideoPlayerActivity.class);
        intent.putExtra(EXTRA_KEY_URL, videoUrl);
        intent.putExtra(EXTRA_KEY_TITLE, title);
        context.startActivity(intent);

    }

    public static final String EXTRA_KEY_URL = "extra_key_url";
    public static final String EXTRA_KEY_TITLE = "extra_key_title";
    private static final int WHAT_PREPARE_VIDEO = 10000;
    private static final int WHAT_UPDATE_PROGRESS = 10001;
    private static final int MAX_PROGRESS = 100;

    TextureView texture_view;
    RelativeLayout rl_root;
    ProgressBar pb;
    MediaPlayer mMediaPlayer;
    Surface mSurface;
    LinearLayout ll_pb;
    TextView tv_during;
    TextView tv_progress;
    SeekBar seek_bar;
    ImageView iv_play_or_pause;

    private String mVideoUrl;
    private int mVideoWidth, mVideoHeight;
    private int mRotation;
    private String title = null;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        title = getIntent().getStringExtra(EXTRA_KEY_TITLE);
        setContentView(R.layout.base_activity_video_player);
        ButterKnife.bind(this);
        findView();
        mVideoUrl = getIntent().getStringExtra(EXTRA_KEY_URL);
        // mVideoUrl="http://mp4.51marryyou.com/ee6d15a5f8cb4b88b204d28d46b07213/b8b36989c3f745abb1c34bb28b90b676-5287d2089db37e62345123a1be272f8b.mp4?auth_key=1532656841-0-0-5d4dbe9e859c6e675e290de50cebfe5b";
        texture_view.setSurfaceTextureListener(this);


        seek_bar.setMax(MAX_PROGRESS);


    }

    private void findView() {
        texture_view = $(R.id.texture_view);
        rl_root = $(R.id.rl_root);
        pb = $(R.id.pb);
        tv_during = $(R.id.tv_during);
        ll_pb = $(R.id.ll_pb);
        tv_during = $(R.id.tv_during);
        tv_progress = $(R.id.tv_progress);
        seek_bar = $(R.id.seek_bar);
        iv_play_or_pause = $(R.id.iv_play_or_pause);

        texture_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                beginDelayedTransition();

                if (mMediaPlayer != null) {
                    if (mMediaPlayer.isPlaying()) {
                        if (iv_play_or_pause.getVisibility() == View.VISIBLE) {
                            iv_play_or_pause.setVisibility(View.GONE);
                        } else {
                            iv_play_or_pause.setVisibility(View.VISIBLE);
                        }
                    } else {
                        iv_play_or_pause.setVisibility(View.VISIBLE);
                    }
                }

            }
        });
        iv_play_or_pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mMediaPlayer != null) {
                    if (mMediaPlayer.isPlaying()) {

                        iv_play_or_pause.setImageResource(R.drawable.video_play_icon);
                        mMediaPlayer.pause();
                    } else {
                        mMediaPlayer.start();
                        mHandler.sendEmptyMessageDelayed(WHAT_UPDATE_PROGRESS, 300);
                        beginDelayedTransition();
                        iv_play_or_pause.setImageResource(R.drawable.video_pause_icon);
                        iv_play_or_pause.setVisibility(View.GONE);
                        //ll_pb.setVisibility(View.GONE);
                    }

                }
            }
        });
    }

    @Override
    protected void setTitle() {
        mTitleBar.setTitle(title);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WHAT_PREPARE_VIDEO://准备播放
                    //texture_view.setRotation(mRotation);
                    initMediaPlayer(mSurface);
                    //显示loading
                    pb.setVisibility(View.VISIBLE);
                    mMediaPlayer.prepareAsync();

                    break;
                case WHAT_UPDATE_PROGRESS://更新进度

                    if (mMediaPlayer == null) {
                        return;
                    }
                    int cur = mMediaPlayer.getCurrentPosition();
                    int max = mMediaPlayer.getDuration();
                    float percent = cur / (float) max;
                    int progress = (int) (percent * MAX_PROGRESS);
                    seek_bar.setProgress(progress);
                    String curStr = "";
                    cur = cur / 1000;
                    if (cur >= 10) {
                        curStr = "0:" + cur;
                    } else {
                        curStr = "0:0" + cur;
                    }
                    tv_progress.setText(curStr);
                    mHandler.sendEmptyMessageDelayed(WHAT_UPDATE_PROGRESS, 300);
                    break;
            }
        }
    };

    private void getVideoRotation() {
        if (!TextUtils.isEmpty(mVideoUrl)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //获取网络视频信息，必须要传new HashMap<String, String>()
                        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                        retriever.setDataSource(mVideoUrl, new HashMap<String, String>());
                        mRotation = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION));
                        //LogUtil.e("mRotation",mRotation+"");
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        mHandler.sendEmptyMessage(WHAT_PREPARE_VIDEO);
                    }

                }
            }).start();
        } else {
            ToastUtil.showToast(this, "视频不存在");
            finish();
        }


    }


    private void beginDelayedTransition() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            TransitionManager.beginDelayedTransition(rl_root);
        }
    }


    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
        mSurface = new Surface(surface);
        getVideoRotation();


    }

    private void initMediaPlayer(Surface surface) {
        try {
            if (mMediaPlayer == null) {
                mMediaPlayer = new MediaPlayer();
                mMediaPlayer.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);
                mMediaPlayer.setDataSource(mVideoUrl);

                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mMediaPlayer.setSurface(surface);
                mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        mHandler.removeMessages(WHAT_UPDATE_PROGRESS);
                        //显示播放按钮
                        //int currentPoistion= mMediaPlayer.getCurrentPosition()/1000;
                        beginDelayedTransition();
                        tv_progress.setText(tv_during.getText().toString());
                        iv_play_or_pause.setImageResource(R.drawable.video_play_icon);
                        iv_play_or_pause.setVisibility(View.VISIBLE);

                    }
                });
                mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        //隐藏loading
                        int duration = mp.getDuration() / 1000;
                        String durationStr = "";
                        if (duration >= 10) {
                            durationStr = "0:" + duration;
                        } else {
                            durationStr = "0:0" + duration;
                        }
                        tv_during.setText(durationStr);
                        pb.setVisibility(View.GONE);
                        iv_play_or_pause.setImageResource(R.drawable.video_pause_icon);
                        mMediaPlayer.start();

                        //开始更新进度
                        mHandler.sendEmptyMessageDelayed(WHAT_UPDATE_PROGRESS, 300);
                    }
                });

                mMediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
                    @Override
                    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
                        mVideoHeight = mMediaPlayer.getVideoHeight();
                        mVideoWidth = mMediaPlayer.getVideoWidth();
                        updateTextureViewSizeCenter();
                     /*   if (listener!=null){
                            listener.onVideoSizeChanged(mVideoWidth,mVideoHeight);
                        }*/
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //重新计算video的显示位置，让其全部显示并据中
    private void updateTextureViewSizeCenter() {

        float sx = (float) texture_view.getWidth() / (float) mVideoWidth;
        float sy = (float) texture_view.getHeight() / (float) mVideoHeight;

        Matrix matrix = new Matrix();

        //第1步:把视频区移动到View区,使两者中心点重合.
        matrix.preTranslate((texture_view.getWidth() - mVideoWidth) / 2, (texture_view.getHeight() - mVideoHeight) / 2);

        //第2步:因为默认视频是fitXY的形式显示的,所以首先要缩放还原回来.
        matrix.preScale(mVideoWidth / (float) texture_view.getWidth(), mVideoHeight / (float) texture_view.getHeight());

        //第3步,等比例放大或缩小,直到视频区的一边和View一边相等.如果另一边和view的一边不相等，则留下空隙
        if (sx >= sy) {
            matrix.postScale(sy, sy, texture_view.getWidth() / 2, texture_view.getHeight() / 2);
        } else {
            matrix.postScale(sx, sx, texture_view.getWidth() / 2, texture_view.getHeight() / 2);
        }

        texture_view.setTransform(matrix);
        texture_view.postInvalidate();
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
        if (mSurface != null) {
            mSurface = null;
        }
        return true;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {

    }
}
